//app.js
var starscore = require("./templates/starscore/starscore.js");
const siteInfo = {
  siteroot: 'http://www.shopadmin.com/'
}
App({

  api_root: '',

  onLaunch: function () {
    var that = this;
    that.setApiRoot();
    that.getWxappBase();

    // 充值最小金额设置
    that.globalData.recharge_amount_min = 100;
    // 商品分类获取
    that._get('category/lists',{}, res=>{
      var categories = []; //{ id: 0, name: "全品类" }
      categories = res.data.list
      that.globalData.categories = categories
      that.getGoods(0);//获取全品类商品
    }, ()=>{
      that.globalData.onLoadStatus = false
    })
  },

  /**
   * 获取小程序基础信息
   */
  getWxappBase(callback) {
    let App = this;
    App._get('wxapp/base', {}, result => {
      // 记录小程序基础信息
      wx.setStorageSync('wxapp', result.data.wxapp);
      callback && callback(result.data.wxapp);
    }, false, false);
  },

  /**
   * 设置当前页面标题
   */
  setTitle() {
    let App = this,
      wxapp;
    if (wxapp = wx.getStorageSync('wxapp')) {
      wx.setNavigationBarTitle({
        title: wxapp.navbar.wxapp_title
      });
    } else {
      App.getWxappBase(() => {
        App.setTitle();
      });
    }
  },

  sendTempleMsg: function (orderId, trigger, template_id, form_id, page, postJsonString, emphasis_keyword){
    var that = this;
    wx.request({
      url: 'https://api.it120.cc/' + that.globalData.subDomain + '/template-msg/put',
      method:'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        token: wx.getStorageSync('token'), //登录接口返回的登录凭证
        type: 0, //0 小程序 1 服务号
        module: 'order', //所属模块：immediately 立即发送模板消息；order 所属订单模块
        business_id: orderId, //登录接口返回的登录凭证
        trigger: trigger, //module不为immediately时必填，代表对应的【订单】触发的状态
        template_id: template_id, //模板消息ID
        form_id: form_id, //type=0时必填，表单提交场景下，为 submit 事件带上的 formId；支付场景下，为本次支付的 prepay_id
        url: page, //小程序：点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）；服务号：跳转的网页地址
        postJsonString: postJsonString, //模板消息内容
        emphasis_keyword: emphasis_keyword //小程序："keyword1.DATA" 模板需要放大的关键词，不填则默认无放大
      },
      success: (res) => {
        //console.log(res.data);
      }
    })
  },
  /**
   * 设置api地址
   */
  setApiRoot() {
    let App = this;
    App.api_root = `${siteInfo.siteroot}index.php?s=/api/`;
  },

  /**
   * 执行用户登录
   */
  doLogin() {
    // 保存当前页面
    let pages = getCurrentPages();
    if (pages.length) {
      let currentPage = pages[pages.length - 1];
      "pages/authorize/index" != currentPage.route &&
        wx.setStorageSync("currentPage", currentPage);
    }
    // 跳转授权页面
    wx.navigateTo({
      url: "/pages/authorize/index"
    });
  },

  /**
   * 当前用户id
   */
  getUserId() {
    return wx.getStorageSync('user_id') || 0;
  },

  /**
   * 显示成功提示框
   */
  showSuccess(msg, callback) {
    wx.showToast({
      title: msg,
      icon: 'success',
      success() {
        callback && (setTimeout(() => {
          callback();
        }, 1500));
      }
    });
  },

  /**
   * 显示失败提示框
   */
  showError(msg, callback) {
    wx.showModal({
      title: '友情提示',
      content: msg,
      showCancel: false,
      success(res) {
        // callback && (setTimeout(() => {
        //   callback();
        // }, 1500));
        callback && callback();
      }
    });
  },

  /**
   * get请求
   */
  _get(url, data, success, fail, complete, check_login) {
    let App = this;
    wx.showNavigationBarLoading();

    // 构造请求参数
    data = Object.assign({
      wxapp_id: 10001,
      token: wx.getStorageSync('token')
    }, data);

    // if (typeof check_login === 'undefined')
    //   check_login = true;

    // 构造get请求
    let request = () => {
      wx.request({
        url: App.api_root + url,
        header: {
          'content-type': 'application/json'
        },
        data,
        success(res) {
          if (res.statusCode !== 200 || typeof res.data !== 'object') {
            console.log(res);
            App.showError('网络请求出错');
            return false;
          }
          if (res.data.code === -1) {
            // 登录态失效, 重新登录
            wx.hideNavigationBarLoading();
            App.doLogin();
          } else if (res.data.code === 0) {
            App.showError(res.data.msg, () => {
              fail && fail()
            });
            return false;
          } else {
            success && success(res.data);
          }
        },
        fail(res) {
          // console.log(res);
          App.showError(res.errMsg, () => {
            fail && fail(res);
          });
        },
        complete(res) {
          wx.hideNavigationBarLoading();
          complete && complete(res);
        },
      });
    };
    // 判断是否需要验证登录
    check_login ? App.doLogin(request) : request();
  },

  /**
   * post提交
   */
  _post_form(url, data, success, fail, complete) {
    wx.showNavigationBarLoading();
    let App = this;
    // 构造请求参数
    data = Object.assign({
      wxapp_id: 10001,
      token: wx.getStorageSync('token')
    }, data);
    wx.request({
      url: App.api_root + url,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      data,
      success(res) {
        if (res.statusCode !== 200 || typeof res.data !== 'object') {
          App.showError('网络请求出错');
          return false;
        }
        if (res.data.code === -1) {
          // 登录态失效, 重新登录
          App.doLogin(() => {
            App._post_form(url, data, success, fail);
          });
          return false;
        } else if (res.data.code === 0) {
          App.showError(res.data.msg, () => {
            fail && fail(res);
          });
          return false;
        }
        success && success(res.data);
      },
      fail(res) {
        // console.log(res);
        App.showError(res.errMsg, () => {
          fail && fail(res);
        });
      },
      complete(res) {
        wx.hideNavigationBarLoading();
        complete && complete(res);
      }
    });
  },

  /**
   * 验证是否存在user_info
   */
  validateUserInfo() {
    let user_info = wx.getStorageSync('userInfo');
    return !!wx.getStorageSync('userInfo');
  },

  /**
   * 对象转URL
   */
  urlEncode(data) {
    var _result = [];
    for (var key in data) {
      var value = data[key];
      if (value.constructor == Array) {
        value.forEach(_value => {
          _result.push(key + "=" + _value);
        });
      } else {
        _result.push(key + '=' + value);
      }
    }
    return _result.join('&');
  },

  /**
   * 验证登录
   */
  checkIsLogin() {
    return wx.getStorageSync('token') != '' && wx.getStorageSync('user_id') != '';
  },

  /**
   * 获取手机号
   */
  getUserPhone(e, callback) {
    let App = this;
    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
      return false;
    }
    wx.showLoading({
      title: "加载中",
      mask: true
    });
    App._post_form('user.index/getUserPhone', {
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv
    }, res => {
      callback && callback(res);
    }, false, () => {
      wx.hideLoading();
    })
  },

  /**
   * 授权登录
   */
  getUserInfo(e, callback) {
    let App = this;
    if (e.detail.errMsg !== 'getUserInfo:ok') {
      return false;
    }
    wx.showLoading({
      title: "正在登录",
      mask: true
    });
    // 执行微信登录
    wx.login({
      success(res) {
        // 发送用户信息
        App._post_form('user/login', {
          code: res.code,
          user_info: e.detail.rawData,
          encrypted_data: e.detail.encryptedData,
          iv: e.detail.iv,
          signature: e.detail.signature
        }, result => {
          // 记录token user_id
          wx.setStorageSync('token', result.data.token);
          wx.setStorageSync('user_id', result.data.user_id);
          // 执行回调函数
          callback && callback();
        }, false, () => {
          wx.hideLoading();
        });
      }
    });
  },

  /**
   * 验证sessionkey状态并更新
   */
  checkWxSession(callback) {
    let App = this;
    wx.checkSession({
      success() {
        console.log('session enable')
        callback && callback();
      },
      fail() {
        console.log('unable')
        // 刷新sessionkey
        wx.login({
          success(res) {
            // 发送用户信息
            App._get('user/refresh', {
              code: res.code,
            }, result => {
              // 执行回调函数
              callback && callback();
            });
          }
        })
      }
    })
  },
  getGoods: function (category_id) {
    var that = this;
    that._get('goods/lists', {
      category_id,
      page: that.globalData.page,
      pageSize: that.globalData.pageSize,
    }, (res)=>{
      that.globalData.goods = []
      var goods = res.data.list.data

      var goodsName = []; //获取全部商品名称，做为智能联想输入库
      for (var i = 0; i < goods.length; i++) {
        goodsName.push(goods[i].goods_name);
      }
      that.globalData.goodsName = goodsName

      var page = that.globalData.page;
      var pageSize = that.globalData.pageSize;
      // 评分
      // for (let i = 0; i < goods.length; i++) {
      //   goods[i].starscore = (goods[i].numberGoodReputation / goods[i].numberOrders) * 5
      //   goods[i].starscore = Math.ceil(goods[i].starscore / 0.5) * 0.5
      //   goods[i].starpic = starscore.picStr(goods[i].starscore)
      // }
      that.globalData.goods = goods   //全部商品
      // console.log(that.globalData.goods)

      // 商品分类
      var categories = that.globalData.categories,
      goodsList = [];
      for (let i = 0; i < categories.length; i++) {
        let listItem = {
          id: categories[i].category_id,
          name: categories[i].name,
          goods: [],
        }
        // id = categories[i].id;
        // key = categories[i].key;
        // name = categories[i].name;
        // typeStr = categories[i].type;
        // let goodsTemp = [];
        for (let j = 0; j < goods.length; j++) {
          if (goods[j].category_id === listItem.id) {
            listItem.goods.push(goods[j])
          }
        }
        // 当activeCategoryId=null和categories的goods不为空，2个条件满足时，设置activeCategoryId为当前的categories的category_id
        // if ((that.globalData.activeCategoryId === null) && (listItem.goods.length > 0)) {
          // 当activeCategoryId=null时，设置activeCategoryId为当前的categories的category_id
        if ((that.globalData.activeCategoryId === null)) {
          that.globalData.activeCategoryId = categories[i].category_id
        }
        goodsList.push(listItem)
      }
      that.globalData.goodsList = goodsList
      that.globalData.onLoadStatus = true
      // console.log('categories:', categories)
    }, ()=>{
      that.globalData.onLoadStatus = false
    });
  },
  globalData:{
    page: 1, //初始加载商品时的页面号
    pageSize: 10000, //初始加载时的商品数，设置为10000保证小商户能加载完全部商品
    categories: [],
    goods: [],
    hotGoods: ['桔', '火龙果', '香蕉', '酸奶', '甘蔗'], //自定义热门搜索商品
    goodsName: [],
    goodsList: [],
    onLoadStatus: true,
    activeCategoryId: null,

    globalBGColor: '#00afb4',
    bgRed: 0,
    bgGreen: 175,
    bgBlue: 180,
    userInfo: null,
    subDomain: "tggtest",// 商城后台个性域名tgg
    version: "2.0.6",
    shareProfile: '   一流的服务，做超新鲜的水果' // 首页转发的时候术语
  }
  // 根据自己需要修改下单时候的模板消息内容设置，可增加关闭订单、收货时候模板消息提醒
})
